package com.zycfc.zsf.boot.mq.rabbitmq.consumer;

import org.springframework.amqp.rabbit.listener.*;
import com.zycfc.zsf.boot.mq.rabbitmq.destinations.*;
import org.springframework.amqp.rabbit.connection.*;
import org.springframework.util.*;
import com.zycfc.zsf.boot.mq.rabbitmq.converter.*;
import org.springframework.amqp.support.converter.*;
import com.zycfc.zsf.boot.mq.common.*;
import javax.annotation.*;
import org.springframework.context.*;
import org.slf4j.*;
import org.springframework.amqp.rabbit.core.*;
import com.rabbitmq.client.*;
import com.zycfc.zsf.boot.logback.util.*;
import com.zycfc.zsf.boot.common.context.*;
import com.zycfc.zsf.boot.core.common.*;
import org.springframework.amqp.core.*;
import com.zycfc.zsf.boot.util.text.*;
import com.zycfc.zsf.boot.mq.rabbitmq.type.*;
import java.util.*;
import com.zycfc.zsf.boot.util.json.*;
import com.zycfc.zsf.boot.util.net.*;
import com.zycfc.zsf.boot.mq.rabbitmq.handler.*;
import com.zycfc.zsf.boot.core.web.data.*;
import com.zycfc.zsf.boot.util.http.*;

public final class SimpleMessageConsumer<T> extends SimpleMessageListenerContainer
{
    private static final Logger log;
    private final IDestination destination;
    private final String namespace;
    
    public SimpleMessageConsumer(final ConnectionFactory connectionFactory, final IDestination destination, final MessageHandler<T> messageHandler, final boolean autoGetAmqpMessage, final String namespace) {
        if (null == destination) {
            throw new IllegalArgumentException("destination \u53c2\u6570\u4e0d\u80fd\u4e3anull");
        }
        if (null == messageHandler) {
            throw new IllegalArgumentException("messageHandler \u53c2\u6570\u4e0d\u80fd\u4e3anull");
        }
        this.destination = destination;
        this.setConnectionFactory(connectionFactory);
        this.setAcknowledgeMode(AcknowledgeMode.AUTO);
        final MessageHandlerAdapter<T> handlerAdapter = new MessageHandlerAdapter<T>(this, messageHandler);
        this.setErrorHandler((ErrorHandler)handlerAdapter);
        this.setMessageListener((Object)handlerAdapter);
        final JsonMessageConverter converter = new JsonMessageConverter(messageHandler.getType());
        converter.setAutoGetAmqpMessage(autoGetAmqpMessage);
        this.setMessageConverter((MessageConverter)converter);
        this.namespace = namespace;
    }
    
    public SimpleMessageConsumer(final ConnectionFactory connectionFactory, final IDestination destination, final MessageHandler<T> messageHandler, final String namespace) {
        this(connectionFactory, destination, messageHandler, true, namespace);
    }
    
    public SimpleMessageConsumer(final ConnectionFactory connectionFactory, final IDestination destination, final MessageHandler<T> messageHandler) {
        this(connectionFactory, destination, messageHandler, true, MqEnvConstants.getInstance().getNamespace());
    }
    
    @PostConstruct
    public void declareAll() {
        try {
            RabbitAdmin rabbitAdmin = this.getRabbitAdmin();
            if (null == rabbitAdmin) {
                rabbitAdmin = (RabbitAdmin)this.getApplicationContext().getBean((Class)AmqpAdmin.class);
                this.setRabbitAdmin(rabbitAdmin);
            }
            this.destination.resetName(MqEnvConstants.getInstance().getNamespace(), this.destination);
            if (!this.destination.isDefaultExchange()) {
                rabbitAdmin.declareExchange((Exchange)this.destination.exchange());
            }
            rabbitAdmin.declareQueue(this.destination.queue());
            rabbitAdmin.declareBinding(this.destination.binding());
            this.setQueues(new Queue[] { this.destination.queue() });
        }
        catch (Throwable e) {
            SimpleMessageConsumer.log.error(e.getMessage(), e);
        }
    }
    
    public IDestination getDestination() {
        return this.destination;
    }
    
    public String getNamespace() {
        return this.namespace;
    }
    
    static /* synthetic */ ApplicationContext access$100(final SimpleMessageConsumer x0) {
        return x0.getApplicationContext();
    }
    
    static {
        log = LoggerFactory.getLogger((Class)SimpleMessageConsumer.class);
    }
    
    private static class MessageHandlerAdapter<T> implements ChannelAwareMessageListener, ErrorHandler
    {
        private static final Logger log;
        private final SimpleMessageConsumer<T> consumer;
        private final MessageHandler<T> handler;
        private DbProcessProvider dbProcessProvider;
        
        protected MessageHandlerAdapter(final SimpleMessageConsumer<T> consumer, final MessageHandler<T> handler) {
            this.consumer = consumer;
            this.handler = handler;
        }
        
        public void onMessage(final Message message, final Channel channel) throws Exception {
            TraceUtil.beginApplilcatonName();
            final MessageProperties messageProperties = message.getMessageProperties();
            String messageId = null;
            String appId = null;
            Date timestamp = null;
            String correlationId = null;
            if (null != messageProperties) {
                messageId = messageProperties.getMessageId();
                messageProperties.getCorrelationId();
                appId = messageProperties.getAppId();
                timestamp = messageProperties.getTimestamp();
                correlationId = messageProperties.getCorrelationId();
                TraceUtil.beginZycfcTrace(messageProperties.getConsumerQueue() + "#" + messageId);
                ZsfRootContext.put(TraceUtil.getZycfcTraceKeyName(), messageId);
                final Map<String, Object> headers = (Map<String, Object>)messageProperties.getHeaders();
                final String profileActive = ZsfEnvConstants.get(ZsfEnvConstants.PROFILES_ACTIVE_KEY);
                if (headers != null && (EnvNameEnum.sit.name().equals(profileActive) || EnvNameEnum.sit830.name().equals(profileActive) || EnvNameEnum.u3.name().equals(profileActive))) {
                    final Object openSceneObj = headers.get("openScene");
                    String openScene = null;
                    if (openSceneObj != null) {
                        openScene = (String)openSceneObj;
                        ZsfRootContext.put("openScene", openScene);
                    }
                    else if (ZsfRootContext.get("openScene") != null) {
                        ZsfRootContext.remove("openScene");
                    }
                    final Object openBaffleObj = headers.get("openBaffle");
                    String openBaffle = null;
                    if (openBaffleObj != null) {
                        openBaffle = (String)openBaffleObj;
                        ZsfRootContext.put("openBaffle", openBaffle);
                    }
                    else if (ZsfRootContext.get("openBaffle") != null) {
                        ZsfRootContext.remove("openBaffle");
                    }
                    MessageHandlerAdapter.log.debug("onMessage-openScene:{}-openBaffle:{}", (Object)openScene, (Object)openBaffle);
                }
            }
            if (null != timestamp) {
                final long messageAge = System.currentTimeMillis() - timestamp.getTime();
                if (messageAge > 120000L) {
                    MessageHandlerAdapter.log.warn("queue:{}, exchange:{}, messageId:{}, from app:{}, message age:{}ms,header:{}", new Object[] { ((SimpleMessageConsumer<Object>)this.consumer).destination.queue().getName(), ((SimpleMessageConsumer<Object>)this.consumer).destination.exchange().getName(), messageId, appId, messageAge, messageProperties.getHeaders() });
                }
                else if (MessageHandlerAdapter.log.isDebugEnabled()) {
                    MessageHandlerAdapter.log.debug("queue:{}, exchange:{}, messageId:{}, from app:{}, message age:{}ms,header:{}", new Object[] { ((SimpleMessageConsumer<Object>)this.consumer).destination.queue().getName(), ((SimpleMessageConsumer<Object>)this.consumer).destination.exchange().getName(), messageId, appId, messageAge, messageProperties.getHeaders() });
                }
            }
            final Map<String, Object> providerHeaders = (Map<String, Object>)messageProperties.getHeaders();
            final Map<String, Object> arguments = (Map<String, Object>)this.consumer.getDestination().exchange().getArguments();
            if (!this.isRevceiveFlag(providerHeaders, arguments)) {
                MessageHandlerAdapter.log.error("\u6d88\u606f\u88ab\u8fc7\u6ee4\uff0c\u4e0d\u4f1a\u88ab\u6d88\u8d39\u5904\u7406,messageId:{},correlationId:{}", (Object)messageId, (Object)correlationId);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            T data = null;
            switch (this.consumer.getAcknowledgeMode()) {
                case MANUAL: {
                    try {
                        final T object = data = (T)this.consumer.getMessageConverter().fromMessage(message);
                        this.handler.onMessage(messageId, correlationId, object, messageProperties);
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    }
                    catch (Throwable e) {
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                        MessageHandlerAdapter.log.error(messageId + ":" + e.getMessage(), e);
                        this.doCollenctErrMessage(data, data.getClass(), messageProperties);
                        this.handler.onError(e);
                    }
                    finally {
                        TraceUtil.endTrace();
                    }
                    break;
                }
                default: {
                    try {
                        final T object = data = (T)this.consumer.getMessageConverter().fromMessage(message);
                        this.handler.onMessage(messageId, correlationId, object, messageProperties);
                    }
                    catch (Throwable e) {
                        MessageHandlerAdapter.log.error(messageId + ":" + e.getMessage(), e);
                        this.doCollenctErrMessage(data, data.getClass(), messageProperties);
                        this.handler.onError(e);
                    }
                    finally {
                        TraceUtil.endTrace();
                    }
                    break;
                }
            }
        }
        
        private boolean isRevceiveFlag(final Map<String, Object> providerHeaders, final Map<String, Object> arguments) {
            boolean flag = false;
            if (arguments == null || arguments.size() <= 1) {
                return true;
            }
            final String matchType = arguments.get("x-match");
            if (StringUtils.isEmpty(matchType)) {
                return true;
            }
            final Iterator<String> it = arguments.keySet().iterator();
            final int plainCount = providerHeaders.size() - 1;
            int calaCount = 0;
            while (it.hasNext()) {
                final String key = it.next();
                if ("x-match".equals(key)) {
                    continue;
                }
                final String val = String.valueOf(arguments.get(key));
                final String providerVal = String.valueOf(providerHeaders.get(key));
                if (!val.equals(providerVal)) {
                    continue;
                }
                if (HeaderMatchType.ANY.getValue().equals(matchType)) {
                    flag = true;
                    break;
                }
                ++calaCount;
            }
            if (HeaderMatchType.ALL.getValue().equals(matchType) && plainCount == calaCount) {
                flag = true;
            }
            return flag;
        }
        
        public void handleError(final Throwable t) {
            this.handler.onError(t);
        }
        
        private void doCollenctErrMessage(final Object data, final Class clazz, final MessageProperties messageProperties) {
            final String messageId = messageProperties.getMessageId();
            final String correlationId = messageProperties.getCorrelationId();
            final String queueName = messageProperties.getConsumerQueue();
            final Date optTime = messageProperties.getTimestamp();
            final String dataJson = JsonUtils.objectToJson(data);
            final String ip = NetUtils.getLocalAddress().getHostAddress();
            final String applicationName = MqEnvConstants.getInstance().getApplicationName();
            if (this.consumer.getDestination().getSaveErrFlag()) {
                final TSysMqConsumerErrs err = new TSysMqConsumerErrs(applicationName, messageId, queueName, dataJson, correlationId, clazz.getName(), optTime);
                if (this.dbProcessProvider == null) {
                    this.dbProcessProvider = (DbProcessProvider)SimpleMessageConsumer.access$100((SimpleMessageConsumer<Object>)this.consumer).getBean((Class)DbProcessProvider.class);
                }
                this.dbProcessProvider.saveConsumerErrLog(err);
            }
            final ErrMessageDatatRequest request = new ErrMessageDatatRequest(dataJson, ip, messageId, correlationId, queueName, clazz.getName());
            request.setRequestData(JsonUtils.objectToJson(data));
            try {
                String url = MqEnvConstants.getInstance().getErrNotifyUrl();
                if (StringUtils.isEmpty(url)) {
                    return;
                }
                if (!url.endsWith("/")) {
                    url += "/";
                }
                url += "api/mq/errNotify";
                request.setApplicationName(applicationName);
                final DataResponse<?> response = (DataResponse<?>)HttpClientUtils.postForObject(url, (Object)request, (Class)DataResponse.class);
                if (!"0000000".equals(response.getCode())) {
                    MessageHandlerAdapter.log.info("data collect fail:{}", (Object)response.getCode());
                }
            }
            catch (Exception e) {
                MessageHandlerAdapter.log.error("data collect error", (Throwable)e);
            }
        }
        
        static {
            log = LoggerFactory.getLogger((Class)MessageHandlerAdapter.class);
        }
    }
}
